package org.chen.wordwave.tools.calendar;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.chen.wordwave.R;
import org.chen.wordwave.act.adapter.CalendarAdapter;
import org.chen.wordwave.bean.CalendarDate;
import org.chen.wordwave.bean.CalendarStatus;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.init.WordInit;
import org.litepal.LitePal;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class WordCalendar extends LinearLayout {
    private TextView tv_year_month,sigin_gift;
    private int lxqd = 0;
    private int ljqd = 0;
    private View yearAndMonth, week, tips;
    private RecyclerView rvDateList;
    private Context mContext;
    private CalendarAdapter calendarAdapter;
    private List<CalendarDate> calendarDateList;
    private UserInfo currentUser;
    public void setLxqd(int lxqd) {
        this.lxqd = lxqd;
    }
    public void setLjqd(int ljqd) {
        this.ljqd = ljqd;
    }
    public int getLxqd() {
        return lxqd;
    }
    public int getLjqd() {
        return ljqd;
    }

    public WordCalendar(Context context) {
        super(context);
        init(context);
    }

    public WordCalendar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public WordCalendar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
        this.setOrientation(VERTICAL);
        calendarDateList = new ArrayList<>();
        calendarAdapter = new CalendarAdapter(calendarDateList, mContext);
        yearAndMonth = View.inflate(mContext, R.layout.custom_year_month, null);
        tv_year_month = yearAndMonth.findViewById(R.id.tv_year_month);
        week = View.inflate(mContext, R.layout.custom_week, null);
        rvDateList = new RecyclerView(mContext);
        rvDateList.setLayoutManager(new GridLayoutManager(mContext, 7));
        rvDateList.setAdapter(calendarAdapter);
        tips = View.inflate(mContext, R.layout.custom_tips, null);
        sigin_gift = tips.findViewById(R.id.sigin_gift);
        sigin_gift.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showGiftDialog();
            }
        });
        this.addView(yearAndMonth);
        this.addView(week);
        this.addView(rvDateList);
        this.addView(tips);

        // 获取当前用户
        currentUser = getCurrentUser();

        if (currentUser != null) {
            ljqd = currentUser.getTotalSignInDays();
            lxqd = currentUser.getConsecutiveSignInDays();
        }

        getDateList(new Date());
    }
    private void showGiftDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle(R.string.sign_gift);

        String message = mContext.getString(R.string.sign_gift_message);

        builder.setMessage(message);
        builder.setPositiveButton(mContext.getString(R.string.know), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }
    private UserInfo getCurrentUser() {
        String email = WordInit.userInfo.getEmail();
        UserInfo user = LitePal.where("email = ?", email).findFirst(UserInfo.class);
        if (user != null && user.getSignedInDates() == null) {
            user.setSignedInDates(new ArrayList<>());  // 初始化签到日期列表
            user.save();
        }
        return user;
    }

    private void getDateList(Date date) {
        tv_year_month.setText(CalendarUtil.getYearAndMonth(date));
        calendarDateList.clear();
        int isWeek = CalendarUtil.getDayIsWeek(date);
        int days = CalendarUtil.getDaysOfMonth(date);
        int day = CalendarUtil.getDayForDate(date);

        // 获取用户签到状态
        List<String> signedInDates = currentUser.getSignedInDates();
        Log.d("FlyerWordCalendar", "signedInDates: " + signedInDates);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        for (int i = 1; i < isWeek; i++) {
            calendarDateList.add(new CalendarDate(0, CalendarStatus.BLANK));
        }

        for (int i = 1; i <= days; i++) {
            calendar.set(Calendar.DAY_OF_MONTH, i);
            String dateStr = sdf.format(calendar.getTime());
            CalendarStatus status = CalendarStatus.OTHER;

            if (i == day) {
                status = CalendarStatus.TODAY;
            } else if (signedInDates.contains(dateStr)) {
                status = CalendarStatus.SIGNED_IN;
            } else {
                status = CalendarStatus.NOT_CHECKED_IN;
            }

            calendarDateList.add(new CalendarDate(i, status));
        }

        getDateNumbers(day, isWeek);
        calendarAdapter.notifyDataSetChanged();
    }

    public void getDateNumbers(int day, int week) {
        ljqd = 0;
        lxqd = 0;

        // 获取累计签到天数
        for (CalendarDate c : calendarDateList) {
            if (c.getCalendarStatus() == CalendarStatus.SIGNED_IN) {
                ljqd++;
            }
        }

        // 获取连续签到天数
        boolean resetConsecutive = false;
        for (int i = calendarDateList.size() - 1; i >= 0; i--) {
            if (calendarDateList.get(i).getCalendarStatus() == CalendarStatus.SIGNED_IN) {
                lxqd++;
            } else if (calendarDateList.get(i).getCalendarStatus() == CalendarStatus.NOT_CHECKED_IN) {
                resetConsecutive = true;
                break;
            }
        }
        Log.e("resetConsecutive1", String.valueOf(resetConsecutive));
        if (resetConsecutive && currentUser != null) {
            Log.e("resetConsecutive2", String.valueOf(resetConsecutive));
            currentUser.resetConsecutiveSignIn();
        }

        Log.e("ljqd", String.valueOf(ljqd));
        Log.e("lxqd", String.valueOf(lxqd));
        // 更新用户数据
        if (currentUser != null && ljqd != 0 && lxqd != 0) {
            currentUser.setTotalSignInDays(ljqd);
            currentUser.setConsecutiveSignInDays(lxqd);
            Log.e("FlyerWordCalendar",currentUser.toString());
            currentUser.save();
        }
    }
    public void updateSignInStatus(UserInfo userInfo) {
        String today = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        List<String> signedInDates = userInfo.getSignedInDates();
        if (signedInDates == null) {
            signedInDates = new ArrayList<>();
        }
        if (!signedInDates.contains(today)) {
            signedInDates.add(today);
            userInfo.setSignedInDates(signedInDates);
            Log.e("FlyerWordCalendar-updateSignInStatus",userInfo.toString());
            userInfo.saveOrUpdate("email",userInfo.getEmail()); // 保存更新后的签到日期列表
        }
    }
}
